package com.mao.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mao.common.Result;
import com.mao.entity.User;
import com.mao.service.UserService;
import com.mao.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取邮箱号
        //相当于发送短信定义的String to
        String email = user.getPhone();
        String subject = "丑团外卖";
        //StringUtils.isNotEmpty字符串非空判断
        if (StringUtils.isNotEmpty(email)) {
            //发送一个四位数的验证码,把验证码变成String类型
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            String text = "【丑团外卖】您好，您的登录验证码为：" + code + "，有效期在5分钟内，请尽快登录！";
            log.info("验证码为：" + code);
            //发送短信
            userService.sendMsg(email,subject,text);
            //将验证码保存到session当中
//            session.setAttribute(email,code);
            //改用redis保存验证码，并设置5分钟保存时间
            redisTemplate.opsForValue().set(email,code,5, TimeUnit.MINUTES);
            return Result.success("验证码发送成功");
        }
        return Result.error("验证码发送异常，请重新发送");
    }

    @PostMapping("/login")
    public Result<User> login(@RequestBody Map map, HttpSession session){
//        log.info(map.toString());
        //1.获取用户自己输入的手机号
        String email =  map.get("phone").toString();
        //2.获取用户自己输入的验证码
        String code =  map.get("code").toString();
        //3.通过session获取之前用户点击请求验证码发送时保存的对应手机号的验证码
//        String codeSession = (String) session.getAttribute(email);
        //改成通过redis获取对应验证码
        Object codeSession = redisTemplate.opsForValue().get(email);
        //4.对比验证码是否一致
        if (codeSession!=null){
            if (!code.isEmpty()&&codeSession.equals(code)){
            //如果比对正确，则登录成功
            LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,email);
            User user = userService.getOne(queryWrapper);
            //如果在数据库没查到该用户，则自动创建该用户
                if (user==null){
                user =new User();
                user.setPhone(email);
                userService.save(user);
                    }
            //要保存用户session到浏览器，否则会被拦截
            session.setAttribute("user",user.getId());

            //验证完毕将redis的验证码删除
            redisTemplate.delete(email);
            return Result.success(user);
            }
        }
        return Result.error("登录失败，验证码或者邮箱号码错误！");
    }

    @PostMapping("/loginout")
    public Result<String> logout(HttpSession session){
        userService.logout(session);
        return Result.success("成功退出");
    }

}
